import React, { useState } from 'react';
import { Upload, message, Button } from 'antd';
import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons';
import Lbxins from "../../api/lbxin";
import SparkMD5 from 'spark-md5'
import "./index.less"
// import { string } from 'prop-types';
const spark = new SparkMD5()    //创建SparkMD5的实例
interface IFileUploadProps {
}


const FileUpload: React.FunctionComponent<IFileUploadProps> = (props) => {
  const uploadProps = {
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info:any) {
      console.log(info,'log-info-------')
      // calculate(data,function(md5){
      //   console.log(md5)//hash值
      // })
      setfileList(info.fileList)
    },
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: (percent:any) => `${parseFloat(percent.toFixed(2))}%`,
    }
  };
  // 生成文件切片
  const createFileChunk = (file:any, size = 10*1024*1024) => {
    const fileChunkList = [];
    // console.log(file,'log-file')
    let cur = 0;
    while (cur < file.size) {
      fileChunkList.push({ name:file.name, file: file.originFileObj.slice(cur, cur + size) });
      cur += size;
    }
    return fileChunkList;
  }
  const update = (data:any,index:number) => {
    Lbxins.postData("/default/uploadFile",data,{headers:{'Content-Type': 'multipart/form-data'}})
      .then(res => {
        // res.data.map((res: { [x: string]: boolean }) => {
        //   return res["CardToolTipShow"] = false;
        // });
        // console.log(res,'log-res-upload')
        
      })
      .catch(err => {
        console.log(err, "log-err")
      });
  }
  const [fileList, setfileList] = useState([])
  // 生成文件 hash（web-worker）
  const calculateHash = (fileChunkList:any) => {
    return new Promise(resolve => {
      // const worker = new Worker("../../assets/js/hash");
      // worker.postMessage({ fileChunkList });
      
      // worker.onmessage = (e:any) => {
      // console.log(e.data,'log-sliceData',typeof e.data,Object.keys(e.data))
      //   const { percentage, hash } = e.data;
      //   // this.hashPercentage = percentage;
      //   if (hash) {
      //     console.log(percentage,'hashhash---', hash);

      //     resolve(hash);
      //   }
      // };
    });
  }
  const optionsFile = async () => {
    let sliceFileLIst:any = createFileChunk(fileList[0])
    spark.appendBinary(sliceFileLIst[0].file)
    let hashData = spark.end()
    let data = {
      fileName: sliceFileLIst[0].name,
      fileHash: hashData
    }
    Lbxins.postData("/default/optionsFile",data)
      .then(res => {
        console.log(res,'log-res')
        UploadFile()
        // res.data.map((res: { [x: string]: boolean }) => {
        //   return res["CardToolTipShow"] = false;
        // });
        // console.log(res,'log-res-upload')
        
      })
      .catch(err => {
        console.log(err, "log-err")
      });
  }
  const calculate = (file:any,callBack:any) => {  
    var fileReader = new FileReader(),  
        blobSlice = File.prototype.slice,  
        chunkSize = 2097152,  
        // read in chunks of 2MB  
        chunks = Math.ceil(file.size / chunkSize),  
        currentChunk = 0,  
        spark = new SparkMD5();  
  
    fileReader.onload = function(e:any) {  
        spark.appendBinary(e.target.result); // append binary string  
        currentChunk++;  
  
        if (currentChunk < chunks) {  
            loadNext();  
        }  
        else {  
            callBack(spark.end());
        }  
    };  
  
    function loadNext() {  
        var start = currentChunk * chunkSize,  
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;  
  
        fileReader.readAsBinaryString(blobSlice.call(file, start, end));  
    };  
  
    loadNext();  
  }
  const UploadFile = async ()=> {
    let sliceFileLIst:any = createFileChunk(fileList[0])
    let sliceData:any = sliceFileLIst.map((res:any,index:number) => {
      let formData = new FormData()
      formData.append('index',index.toString())  //切片序号
      formData.append('fileSize',sliceFileLIst.length.toString())  //总切片大小 
      formData.append('file',res.file)
      formData.append('fileName',res.name)
      spark.appendBinary(res.file)
      let hashData = spark.end()
      console.log(hashData,'log-hashData------------------',res.file)
      
      formData.append('fileHash',hashData + "-" +index) // append array buffe)  SparkMD5.hashBinary(e.target.result)
      return formData
    })
    
    // calculateHash(sliceFileLIst)
    for (let i = 0; i < sliceData.length; ) {
      await update(sliceData[i],i)
      i++
    }
    await Promise.all(sliceData) // 并发切片
  }
  return (
    <div className="FileUploadBox contentBox">
      <div className="uploadBtn">
        <Upload {...uploadProps} fileList={fileList}>
          <Button disabled={fileList.length>0}>Click to Upload</Button>
        </Upload>
        <Button icon={<PauseCircleOutlined />} onClick={()=>{optionsFile()}}>上传</Button>
        <Button icon={<PlayCircleOutlined />}>暂停</Button>
      </div>
    </div>
  );
};

export default FileUpload;
